import queue
import threading
import json
import requests
import time
import datetime
import sys
import re
from typing import TextIO
from abc import ABC, abstractmethod


class ILog(ABC):
    @abstractmethod
    def doLog(self, data: str):
        pass


class LogInterceptor:
    def __init__(self, target: ILog, original_stdout: TextIO = sys.stdout):
        self.original_stdout = original_stdout
        self.target = target
        sys.stdout = self

    def __del__(self):
        return self.stop()

    def stop(self) -> None:
        sys.stdout = self.original_stdout

    def write(self, message):
        self.target.doLog(message)
        return self.original_stdout.write(message)

    def flush(self) -> None:
        return self.original_stdout.flush()


wx_webhook = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=f5633b3b-79ee-4c4f-b9f9-6c7f77dc5747"


def send_text(webhook, content) -> requests.Response:
    header = {
        "Content-Type": "application/json",
        "Charset": "UTF-8"
    }
    data = {
        "msgtype": "text",
        "text": {
            "content": content,
            "mentioned_list": []
        }
    }
    data = json.dumps(data)
    info = requests.post(url=webhook, data=data, proxies=None, headers=header)
    return info


class WxLog(ILog):
    def __init__(self) -> None:
        super().__init__()
        self.t = threading.Thread(target=log_run, args=[self])
        self.logQueue = queue.Queue()
        self.t.daemon = True
        self.t.start()

    def table_process(self, data: str):
        lines = data.split("\n")
        result = "\n"
        for line in lines:
            matches = re.findall(r'[^\|^\s]+', line)
            if matches != None and len(matches) == 2:
                result += f"{matches[0]}:\t{matches[1]}\n"
        return result

    def doLog(self, data: str):
        if data == "\n":
            return
        elif data.startswith("-----"):
            data = self.table_process(data)
        self.logQueue.put(
            f"[{datetime.datetime.now()}]\t{data}\n", block=False)
        pass

    def send(self, data):
        try:
            send_text(wx_webhook, data)
        except:
            return
        # return super().doLog(data)


def log_run(target: WxLog):
    while True:
        data = ""
        while not target.logQueue.empty():
            data += target.logQueue.get(False)
        if data != "":
            target.send(data)
        time.sleep(60)


if __name__ == "__main__":
    li = LogInterceptor(WxLog())
    print("test")
